﻿namespace LeadMaster.Controllers
{
    using System;
    using System.Linq;
    using System.Web.Mvc;
    using LeadMaster.DAL;
    using LeadMaster.ViewModels;
    using System.Web.Security;
    using LeadMaster.Helpers;
    using System.Collections.Generic;
    using LeadMaster.Models;
    using System.Data;
    using LeadMaster.Properties;
    using System.Configuration;
    using System.Data.Entity;
    using System.Data.Entity.Core.Objects;

  public class ClientController : Controller
    {

      private DunsmoreContext db = new DunsmoreContext();

      private int GetID()
      {
        Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
        int clientID = db.ClientUsers.Where(m => m.UserID == currentUser).Select(m => m.CompanyID??0).FirstOrDefault();
        return clientID;
      }

      public void ReturnedLeads()
      {

      }

      public ActionResult ChangeLeadStatus(int id, string element)
      {
          ViewModelLeadStatus viewModel = new ViewModelLeadStatus();
          LeadResults leadResult = db.LeadResults.Find(id);
          viewModel.LeadStatus = db.LeadStatus.Where(m => m.LeadID == leadResult.LeadID && m.BlockID == leadResult.BlockId).FirstOrDefault();
          if (Roles.GetRolesForUser(User.Identity.Name).Contains(ApplicationRoles.Client))
          {
              ViewBag.LeadStatus_LeadFlagsID = new SelectList(db.LeadFlags.Where(m => m.WithClient == true && m.LeadFlagsID>2), "LeadFlagsID", "Description");
          }

          ViewBag.LeadResultsID = id;
          viewModel.Element = element;
          return PartialView(viewModel);
      }

      [HttpPost]
      public void ChangeLeadStatus(ViewModelLeadStatus viewModelLeadStatus)
      {
          if (ModelState.IsValid && viewModelLeadStatus.LeadStatus.LeadFlagsID>0)
          {
              db.Entry(viewModelLeadStatus.LeadStatus).State = EntityState.Modified;
              if (viewModelLeadStatus.LeadStatus.LeadFlagsID>1)
              {
                db.SaveChanges();  
              }
          }
      }

      public ActionResult ChangeLeadReason(int id)
      {
        LeadResults lr = db.LeadResults.Find(id);
        LeadStatus leadStatus = db.LeadStatus.Where(m => m.LeadID == lr.LeadID && m.BlockID==lr.BlockId).FirstOrDefault();
        ViewBag.LeadReasons = db.LeadReasons.Where(m => m.ClientReasons == true).Where(m => m.LeadReasonsID > 1 && m.LeadReasonsID != 47 && m.Description != "Mandatory information wrong").ToList();
        int leadTemplateID = db.Leads.Find(leadStatus.LeadID).LeadTemplateID ?? 0;

        List<string> statMandQuestions = (from ls in db.LeadStatQuestions
                                          join lt in db.LeadStat on ls.LeadStatID equals lt.LeadStatID
                                          join t in db.LeadTemplate on lt.LeadTemplateID equals t.LeadTemplateID
                                          where t.LeadTemplateID == leadTemplateID && ls.Mandatory == true
                                          select ls.Question).ToList();


        List<string> groupMandQuestions = (from lgq in db.LeadGroupQuestions
                                           join lg in db.LeadGroups on lgq.LeadGroupsID equals lg.LeadGroupsID
                                           join t in db.LeadTemplate on lg.LeadTemplateID equals t.LeadTemplateID
                                           where t.LeadTemplateID == leadTemplateID && lgq.Mandatory == true && lg.Title!="Caller Details"
                                           select lgq.Question).ToList();

        List<string> qualifyingQuestions = (from lrs in db.LeadResults
                                            join lgq in db.LeadGroupQuestions on lrs.LeadGroupQuestionsID equals lgq.LeadGroupQuestionsID
                                            join lg in db.LeadGroups on lgq.LeadGroupsID equals lg.LeadGroupsID
                                            where lrs.LeadID == lr.LeadID && lrs.BlockId == lr.BlockId && lg.QualifyingGroup != null && lrs.Answer!=null && lrs.Answer!="No"
                                            select lrs.Question).ToList();

        List<string> ListMandQuestions = new List<string>();
        foreach (var item in statMandQuestions)
        {
          ListMandQuestions.Add(item);
        }
        foreach (var item in groupMandQuestions)
        {
          ListMandQuestions.Add(item);
        }
        foreach (var item in qualifyingQuestions)
        {
          ListMandQuestions.Add(item);
        }

        ViewBag.Manfield = ListMandQuestions;

        return PartialView(leadStatus);
      }

      [HttpPost]
      public void ChangeLeadReason(LeadStatus leadStatus, string newnote)
      {
        leadStatus.Notes += DateTime.Now.ToShortDateString() + " Client Notes : ";
        if (leadStatus.Manfield != "0")
        {
          // Selected an internal mandatory field
          leadStatus.LeadReasonsID = db.LeadReasons.Where(m => m.Description == "Mandatory information wrong").FirstOrDefault().LeadReasonsID;
          leadStatus.LeadReason = db.LeadReasons.Where(m => m.Description == "Mandatory information wrong").FirstOrDefault();
          leadStatus.Notes += "Client Reason - " + leadStatus.Manfield + ". ";
        }
        leadStatus.Notes += newnote + "\n";

        if (leadStatus.LeadFlagsID==2 && leadStatus.LeadReasonsID>1 && leadStatus.LeadReasonsID!=47)  // do not auto-reject if they have selected 'For Client Use Only'
        {
          leadStatus.LeadFlagsID = 8;
        }

        db.Entry(leadStatus).State = EntityState.Modified;
        db.SaveChanges();
      }


      public ActionResult ShowLeads(ViewModelClient viewModel)
      {
        int testrecs = 0;
        try
        {
        int id = GetID();
        viewModel.Leads = db.Leads.Where(m => m.CompanyID == id).FirstOrDefault();
        List<LeadResults> leadResults = db.LeadResults
            .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
            .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID && m.b.LeadFlag.WithClient != null)
            .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
            .Where(m => m.b.LeadFlagsID>1)
            .OrderByDescending(m => m.a.BlockId)
            .ThenBy(m => m.a.DisplayOrder)
            .Select(m => m.a)
            .OfType<LeadResults>()
            .ToList();
        int blockID = 0;
        LeadStatus statusBlock = db.LeadStatus.FirstOrDefault();
        LeadFlags leadFlag = db.LeadFlags.FirstOrDefault();
        LeadReasons leadReason = db.LeadReasons.FirstOrDefault();
        viewModel.FullListLeadResults = new List<ListLeadResults>();
        testrecs = leadResults.Count();
        //viewModel.LeadDate = leadResults.Fir
        int totalLeads = 0;
        foreach (LeadResults item in leadResults)
        {
            ListLeadResults listLeadResults = new ListLeadResults();
            listLeadResults.LeadResult = item;
            if (item.BlockId != blockID)
            {
                statusBlock = db.LeadStatus
                    .Where(m => m.LeadID == item.LeadID && m.BlockID == item.BlockId)
                    .FirstOrDefault();
                leadFlag = db.LeadFlags.Find(statusBlock.LeadFlagsID);
                leadReason = db.LeadReasons.Find(statusBlock.LeadReasonsID);
                totalLeads++;
            }
            blockID = item.BlockId;
            listLeadResults.LeadStatus = statusBlock;
            listLeadResults.LeadFlag = leadFlag;
            listLeadResults.LeadReason = leadReason;

            viewModel.FullListLeadResults.Add(listLeadResults);
        }
        viewModel.Titles = new List<string>();
        
        if (viewModel.FullListLeadResults.Count() > 0)
        {
            int questionCounter = 0;
            foreach (var item in leadResults)
            {
                viewModel.Titles.Add(item.Question);
                questionCounter++;
                if (questionCounter == item.QuestionBlock)
                {
                    questionCounter = 0;
                    break;
                }
            }
        }
        ViewBag.TotalLeads = totalLeads;
        return View(viewModel);
        }
        catch (Exception e)
        {
          ViewBag.ErrorMessage = "Showing Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException + " - num of recs=" + testrecs.ToString();
          return View("Errormessages");
        }
      }

      public ActionResult LeadDates()
      {
        ViewModelClient viewModel = new ViewModelClient();
        int id = GetID();
        viewModel.Leads = db.Leads.Where(m => m.CompanyID == id).FirstOrDefault();
        viewModel.lrDates = db.LeadResults
        .Where(m => m.LeadID == viewModel.Leads.LeadID)
        .OrderByDescending(m => m.BlockId)
        .Select(m => EntityFunctions.TruncateTime(m.LeadDate))
        .Distinct()
        .ToList();
        List<ViewModelClient> viewModels = new List<ViewModelClient>();

        return View("ShowLeadsGroups", viewModel);
      }

      public ActionResult Filter()
      {
          ViewModelClient ViewModel = new ViewModelClient();

          return View(ViewModel);
      }

      [HttpPost]
      public ActionResult Filter(ViewModelClient viewModel)
      {
          viewModel.Postcode= viewModel.Postcode==null ? "*" : viewModel.Postcode;
          viewModel.Surname = viewModel.Surname == null ? "*" : viewModel.Surname;

          try
          {
              int id = GetID();
              viewModel.Leads = db.Leads.Where(m => m.CompanyID == id).FirstOrDefault();
              var leadDates = from ls in db.LeadStatus
                              join lr in db.LeadResults on new { ls.LeadID, ls.BlockID } equals new {LeadID = lr.LeadID, BlockID = lr.BlockId } 
                              where (lr.Question=="Surname" && lr.Answer.Contains(viewModel.Surname)) ||
                                (lr.Question == "Postcode" && lr.Answer.Contains(viewModel.Postcode))
                              where ls.LeadID == viewModel.Leads.LeadID
                              select new { ls.LeadDate };

              var lds = (from ld in leadDates.AsEnumerable()
                         select new { leadtimestamp = ld.LeadDate, orderDate = ld.LeadDate.Substring(6, 4) + ld.LeadDate.Substring(3, 2) + ld.LeadDate.Substring(0, 2) })
                                  .Distinct();

              List<string> leadtimestamps = lds.OrderByDescending(m => m.orderDate).Select(m => m.leadtimestamp).ToList();
              List<string> finalList = new List<string>();
              foreach (var item in leadtimestamps)
              {
                  string totalLeads = leadDates.Where(m => m.LeadDate == item).Count().ToString();
                  finalList.Add(item + " : Total Leads " + totalLeads);
              }
              ViewBag.Postcode = viewModel.Postcode;
              ViewBag.Surname = viewModel.Surname;
              return View("FetchLeadBlock", finalList);

          }
          catch (Exception e)
          {
              ViewBag.ErrorMessage = "Showing Filtered Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
              return View("Errormessages");
          }

      }

      public ActionResult FetchLeadBlock(bool leadReturnsOnly=false)
      {
        try
        {
        ViewModelClient viewModel = new ViewModelClient();
        int id = GetID();
        var qcFlags = new List<int>();
        var actionFlags = new List<int>();
        if (leadReturnsOnly==false)
        {
          qcFlags.Add(2);
          qcFlags.Add(3);
          qcFlags.Add(4);
          qcFlags.Add(6);
          qcFlags.Add(7);
          qcFlags.Add(8);
          Maintenance.inDunsmoreReturnsOnly = false;
          actionFlags.Add(2);
          actionFlags.Add(3);
          actionFlags.Add(6);
        }
        else
        {
          qcFlags.Add(6);
          Maintenance.inDunsmoreReturnsOnly = true;
          actionFlags.Add(6);
        }
        
        
        viewModel.Leads = db.Leads.Where(m => m.CompanyID == id).FirstOrDefault();
        viewModel.ListLeads = db.Leads.Where(m => m.CompanyID == id).ToList();
        var LeadIDs = viewModel.ListLeads.Select(m => m.LeadID).ToList();

        var leadDates = db.LeadStatus
                          .Join(db.Leads, a => a.LeadID, b => b.LeadID, (a, b) => new { LeadStatus = a, Leads = b })
                          .Where(p => LeadIDs
                              .Contains(p.LeadStatus.LeadID))
                          .Where(f => qcFlags.Contains(f.LeadStatus.LeadFlagsID))
                          .Select(m => new { m.LeadStatus.LeadDate });

        var lds = (from ld in leadDates.AsEnumerable()
                   select new { leadtimestamp = ld.LeadDate, orderDate = ld.LeadDate.Substring(6, 4) + ld.LeadDate.Substring(3, 2) + ld.LeadDate.Substring(0, 2) })
                            .Distinct();

        int daysDiff=0;
        List<string> leadtimestamps = lds.OrderByDescending(m => m.orderDate).Select(m => m.leadtimestamp).ToList();
        List<string> finalList=new List<string>();
        foreach (var item in leadtimestamps)
        {
          daysDiff = viewModel.Leads.ReturnDays ?? 6;
          daysDiff += AdditionalDays.AddLeadDays(Convert.ToDateTime(item).DayOfWeek);
          daysDiff -= (Convert.ToInt16((DateTime.Now - (Convert.ToDateTime(item))).TotalDays)); 
          daysDiff = daysDiff < 0 ? 0 : daysDiff;
          string totalLeadsToAction="0";
          string totalLastDay = "0";
          if (daysDiff>0)
          {
            totalLeadsToAction = db.LeadStatus
                          .Where(p => LeadIDs
                              .Contains(p.LeadID))
                          .Where(m => m.LeadDate == item && (actionFlags.Contains(m.LeadFlagsID))).Count().ToString();
          }
          if (daysDiff==1)
          {
            int TotalCorrectDays = db.LeadStatus
                .Where(p => LeadIDs.Contains(p.LeadID))
                .Where(m => m.LeadDate == item && (actionFlags.Contains(m.LeadFlagsID)))
                .Count();

              int TotalLockdowns= db.LeadStatus
                  .Join(db.LeadReasons, a => a.QCLeadReasonsID, b => b.LeadReasonsID, (a,b) => new { LeadStatus=a, LeadReasons=b })
                  .Where(p => LeadIDs.Contains(p.LeadStatus.LeadID))
                  .Where(m => m.LeadStatus.QCLeadReasonsID==m.LeadReasons.LeadReasonsID && (m.LeadReasons.lockdown==null || m.LeadReasons.lockdown==false))
                  .Where(m => m.LeadStatus.LeadDate==item && (actionFlags.Contains(m.LeadStatus.LeadFlagsID)))
                  .Count();

              totalLastDay = (TotalCorrectDays - TotalLockdowns).ToString();
          }

          string totalLeads = db.LeadStatus
                    .Where(m => m.LeadDate == item && (qcFlags.Contains(m.LeadFlagsID)))
                    .Where(p => LeadIDs
                      .Contains(p.LeadID))
                    .Count().ToString();
          string DateTitle;
            DateTitle=item + " : Total Leads " + totalLeads + ". Leads To Action " + totalLeadsToAction;
            DateTitle += totalLastDay == "0" ? string.Empty : ". Last Day To Action " + totalLastDay;
          
            finalList.Add(DateTitle);
        }
        ViewBag.Postcode = "*";
        ViewBag.Surname = "*";

        return View(finalList);
        }
        catch (Exception e)
        {
          ViewBag.ErrorMessage = "Showing Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
          return View("Errormessages");
        }

      }

      public ActionResult ShowLeadsByDate(string leadDate, string surName = "*", string postCode = "*")
      {
          surName = surName.Substring(1, surName.Trim().Length - 2);
          postCode = postCode.Substring(1, postCode.Trim().Length - 2);

          long testrecs = 0;
          try
          {
              ViewModelClient viewModel = new ViewModelClient();
              int id = GetID();
              var qcFlags = new List<int>();
              if (Maintenance.inDunsmoreReturnsOnly == false)
              {
                qcFlags.Add(2);
                qcFlags.Add(3);
                qcFlags.Add(4);
                qcFlags.Add(6);
                qcFlags.Add(8);
              }
              else
              {
                qcFlags.Add(6);
              }

             var LeadIDs = db.Leads.Where(m => m.CompanyID == id).Select(m => m.LeadID).ToList();
             viewModel.Leads = db.Leads.Where(m => m.CompanyID == id).FirstOrDefault();
             bool isStreetView = db.Leads
                 .Where(p => LeadIDs
                   .Contains(p.LeadID))
                 .Any(s => s.StreetView == true);
                

              if (false && isStreetView)
              {
                string companyPostcode = viewModel.Leads.Company.Postcode.Replace(" ", "");
                PostCodes postCodes = db.Postcodes.Where(m => m.Postcode == companyPostcode).FirstOrDefault();
                ViewBag.LatLong = string.Format("{0},{1}", postCodes.lat.ToString(), postCodes.longitude.ToString());
              } 
              leadDate = leadDate.Substring(1, 10);
              List<LeadResults> leadResults = db.LeadResults
                  .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
                  .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID && (qcFlags.Contains(m.b.LeadFlagsID)))
                  .Where(p => LeadIDs
                      .Contains(p.a.LeadID))
                  .Where(m => m.b.LeadDate==leadDate)
                  .OrderByDescending(m => m.a.BlockId)
                  .ThenBy(m => m.a.DisplayOrder)
                  .Select(m => m.a)
                  .OfType<LeadResults>()
                  .ToList();
              if (surName!="*")
              {
                  List<LeadResults> filteredResults = (from lr in leadResults where lr.Question=="Surname" && lr.Answer.ToUpper().Contains(surName.ToUpper()) select lr).ToList();
                  leadResults = leadResults
                                .Join(filteredResults, a => a.LeadID, b => b.LeadID, (a,b) => new {a,b})
                                .Where(m => m.a.LeadID==m.b.LeadID && m.a.BlockId==m.b.BlockId)
                                .OrderByDescending(m => m.a.BlockId)
                                .ThenBy(m => m.a.DisplayOrder)
                                .Select(m => m.a)
                                .OfType<LeadResults>()
                                .ToList();
              }
              if (postCode != "*")
              {
                  List<LeadResults> filteredResults = (from lr in leadResults where lr.Question == "Postcode" && lr.Answer.ToUpper().Contains(postCode.ToUpper()) select lr).ToList();
                  leadResults = leadResults
                                .Join(filteredResults, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
                                .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockId)
                                .OrderByDescending(m => m.a.BlockId)
                                .ThenBy(m => m.a.DisplayOrder)
                                .Select(m => m.a)
                                .OfType<LeadResults>()
                                .ToList();
              }
              int blockID = 0;
              LeadStatus statusBlock = db.LeadStatus.FirstOrDefault();
              LeadFlags leadFlag = db.LeadFlags.FirstOrDefault();
              LeadReasons leadReason = db.LeadReasons.FirstOrDefault();
              viewModel.FullListLeadResults = new List<ListLeadResults>();
              testrecs = 0;
              viewModel.LeadDate = leadResults.LastOrDefault().LeadDate;
              int totalLeads = 0;
              bool lockDown = false;
              foreach (LeadResults item in leadResults)
              {
                  ListLeadResults listLeadResults = new ListLeadResults();
                  listLeadResults.LeadResult = item;
                  if (item.BlockId != blockID)
                  {
                      statusBlock = db.LeadStatus
                          .Where(m => m.LeadID == item.LeadID && m.BlockID == item.BlockId)
                          .FirstOrDefault();
                      leadFlag = db.LeadFlags.Find(statusBlock.LeadFlagsID);
                      leadReason = db.LeadReasons.Find(statusBlock.LeadReasonsID);
                      lockDown = statusBlock.QCLeadReasonsID == null ? false : db.LeadReasons.Find(statusBlock.QCLeadReasonsID).lockdown ?? false;
                      totalLeads++;
                  }
                  blockID = item.BlockId;
                  listLeadResults.LeadStatus = statusBlock;
                  listLeadResults.LeadFlag = leadFlag;
                  listLeadResults.LeadReason = leadReason;
                  listLeadResults.QCReason = statusBlock.QCLeadReasonsID==null ? string.Empty :  db.LeadReasons.Find(statusBlock.QCLeadReasonsID).Description;
                  listLeadResults.Lockdown = lockDown;
                  testrecs = item.LeadResultsID;
                  viewModel.FullListLeadResults.Add(listLeadResults);
              }
              viewModel.GridTitlesList = new List<GridTitles>();

              if (viewModel.FullListLeadResults.Count() > 0)
              {
                  int questionCounter = 0;
                  foreach (var item in leadResults)
                  {
                    GridTitles gridTitle = new GridTitles();
                    gridTitle.Title = item.Question;
                    if (item.LeadStatQuestion != null)
                    {
                      gridTitle.Backcolour = item.LeadStatQuestion.LeadStat.BackgroundColour;
                    }
                    else if (item.LeadGroupQuestion != null)
                    {
                      gridTitle.Backcolour = item.LeadGroupQuestion.LeadGroups.BackgroundColour;
                    }
                      viewModel.GridTitlesList.Add(gridTitle);
                      questionCounter++;
                      if (questionCounter == item.QuestionBlock)
                      {
                          questionCounter = 0;
                          break;
                      }
                  }
              }
              ViewBag.TotalLeads = totalLeads;
              return View("PartialShowLeads", viewModel);
          }
          catch (Exception e)
          {
              ViewBag.ErrorMessage = "Showing Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException + " - num of recs=" + testrecs.ToString();
              return View("Errormessages");
          }
      }

	  public ActionResult PlayVoxFile(string voxFile)
	  {
		  var file = Server.MapPath("~/Vox/" + voxFile);
          if (voxFile.Substring(voxFile.Length-3,3).Equals("mp3"))
          {
              return File(file, "audio/mp3");    
          }
          else
          {
              return File(file, "audio/wav");    
          }
		  
	  }

      public string UpdateElement(string currentElement)
      {
        int firstMarker=currentElement.IndexOf("_");
        int secondMarker=currentElement.LastIndexOf("_");
        int leadID=Convert.ToInt16( currentElement.Substring(firstMarker+1,secondMarker-firstMarker-1));
        int blockID=Convert.ToInt16( currentElement.Substring(secondMarker+1,currentElement.Length-secondMarker-2));
        return db.LeadStatus.Where(m => m.LeadID == leadID && m.BlockID == blockID).FirstOrDefault().LeadFlag.Description;
      }

      public JsonResult UpdateReason(string currentElement)
      {
          int firstMarker = currentElement.IndexOf("_");
          int secondMarker = currentElement.LastIndexOf("_");
          int leadID = Convert.ToInt16(currentElement.Substring(firstMarker + 1, secondMarker - firstMarker - 1));
          int blockID = Convert.ToInt16(currentElement.Substring(secondMarker + 1, currentElement.Length - secondMarker - 2));
          LeadReasonResponse leadReasonResponse = new LeadReasonResponse();
          LeadStatus leadStatus = db.LeadStatus.Where(m => m.LeadID == leadID && m.BlockID == blockID).FirstOrDefault();
          leadReasonResponse.theReason = leadStatus.LeadReason.Description;
          if (leadReasonResponse.theReason=="Mandatory information wrong" && leadStatus.Manfield!=null)
          {
              leadReasonResponse.theReason += ". " + leadStatus.Manfield;
          }
          leadReasonResponse.theNote = db.LeadStatus.Where(m => m.LeadID == leadID && m.BlockID == blockID).FirstOrDefault().Notes;
          leadReasonResponse.elementToUpdate = currentElement.Replace("'","");
          leadReasonResponse.noteToUpdate = leadReasonResponse.elementToUpdate.Replace("reas", "note");
          return Json(leadReasonResponse, JsonRequestBehavior.AllowGet);
      }

      public ActionResult ShowReturnsOnly()
      {
        return RedirectToAction("FetchLeadBlock", new {leadReturnsOnly=true });
      }

      public ActionResult Tracker()
      {
        int companyID = GetID();
        int leadID = db.Leads.Where(m => m.CompanyID == companyID).FirstOrDefault().LeadID;
        return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fClientTracker&rs:Command=Render&l=" + leadID.ToString());
      }


      public void UpdateClientNote(int id,string notetext)
      {
          LeadStatus ls = db.LeadStatus.Find(id);
          ls.ClientNotes=notetext;
          db.Entry(ls).State=EntityState.Modified;
          db.SaveChanges();
      }

      public static string GetColourCode(int leadFlagsID)
      {
        string colourCode;
        switch (leadFlagsID)
        {
          case 2:
            colourCode = "0000FF";
            break;
          case 4:
            colourCode = "228b22";
            break;
          case 8:
            colourCode = "b22222";
            break;
          case 5:
            colourCode = "b22222";
            break;
          default:
            colourCode = "000000";
            break;
        }
        
        return "color: #" + colourCode + ";";
      }

      [System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
      public FileStreamResult ShowExcel(string reportname = "CallCentreStats")
      {
        int companyID = GetID();
        int leadID = db.Leads.Where(m => m.CompanyID == companyID).FirstOrDefault().LeadID;
        string excelname = db.Companies.Find(companyID).Company ;
        // Create a new proxy to the web service
        rsExecService.ReportExecutionService rsExec = new rsExecService.ReportExecutionService();
        // Authenticate to the web service using windows credentials
        rsExec.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["UserID"], ConfigurationManager.AppSettings["Pwd"]);
        // Load the selected report
        rsExec.LoadReport("/dunsmore/" + reportname, null);

        // Prepare Render arguments
        string encoding = String.Empty;
        string mimeType = String.Empty;
        string extension = String.Empty;
        rsExecService.Warning[] warnings = null;
        string[] streamIDs = null;

        // Prepare report parameters.
        rsExecService.ParameterValue[] parameters = new rsExecService.ParameterValue[1];
        parameters[0] = new rsExecService.ParameterValue();
        parameters[0].Value = leadID.ToString();
        parameters[0].Name = "leadid";

        // Set the parameters for the report needed.
        rsExec.SetExecutionParameters(parameters, "en-us");

        //Render the report to a byte[]
        Byte[] byteInfo = rsExec.Render("Excel", null, out extension, out encoding, out mimeType, out warnings, out streamIDs);

        // Return the report as a file stream
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        ms.Write(byteInfo, 0, byteInfo.Length);
        ms.Position = 0;

        HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + excelname + ".xls");

        return new FileStreamResult(ms, ConfigurationManager.AppSettings["ReportName"]);

      }

      public static string StreetviewLatLong(int leadStatusID)
      {
        DunsmoreContext db = new DunsmoreContext();
        LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
        string postCode = db.LeadResults
            .Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID && m.Question == "Postcode")
            .Select(m => m.Answer)
            .FirstOrDefault();
        PostCodes postCodes = db.Postcodes.Where(m => m.Postcode == postCode.Replace(" ", "")).FirstOrDefault();
        string returnString = postCodes != null ? (postCodes.lat.ToString() + "," + postCodes.longitude.ToString()) : string.Empty;
        return returnString;
      }

      public static string StreetviewPostcode(int leadStatusID)
      {
        DunsmoreContext db = new DunsmoreContext();
        LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
        string postCode = db.LeadResults
            .Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID && m.Question == "Postcode")
            .Select(m => m.Answer)
            .FirstOrDefault();
        string returnString = postCode;
        return returnString;
      }

      public ActionResult Escalate(int leadStatusID)
      {
          LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
          return PartialView(leadStatus);
      }

    }
}
